﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using Autenticazione.DB;
using System.Data;

namespace Autenticazione.BusinessObject
{
    internal class Club
    {
        public string EMail;
        public string ClubDescription;
        public string Citta;
        public int IdRegione;
        public string Telefono;
        
        public Club()
        {
        }

        public Club(string email, string club, string citta, int idregione, string telefono)
        {
            this.EMail = email;
            this.ClubDescription = club.Replace("'", "''");
            this.Citta = citta.Replace("'", "''");
            this.IdRegione = idregione;
            this.Telefono = telefono;
            
        }

        public Club GetClub(string email)
        {
            Club c = null;

            SqlDataReader dr = null;
            string strSQL = string.Format(@"select * from Club where Email = '{0}'", email);
            DB.DB db = new DB.DB();

            dr = db.Reader(strSQL);

            if (dr == null)
                return c;

            if (dr.Read())
                c = new Club(dr["Email"].ToString(), dr["Club"].ToString(),
                            dr["Citta"].ToString(),
                            int.Parse(dr["IdRegione"].ToString()),
                            dr["Telefono"].ToString());

            
            db.CloseConnection();

            return c;
        }

        public string Serialize()
        {
            string strSQL = string.Format(@"select * from Club");
            DB.DB db = new DB.DB();
            DataTable dt = db.GetTable(strSQL);

            dt.TableName = "Club";

            System.IO.StringWriter writer = new System.IO.StringWriter();

            dt.WriteXml(writer, XmlWriteMode.IgnoreSchema, true);

            return writer.ToString();
        }

        public Boolean Salva()
        {
            String strSQL = string.Empty;

            if (GetClub(this.EMail) == null)    //insert
                strSQL = string.Format(@"insert into Club (EMail, Club, Citta, IdRegione, Telefono) values ('{0}', '{1}', '{2}', {3}, '{4}')", this.EMail, this.ClubDescription, this.Citta, this.IdRegione.ToString(), this.Telefono);
            else    //update
                strSQL = string.Format(@"Update Club set Club = '{0}', Citta = '{1}', IdRegione = {2}, Telefono = '{3}' where EMail = '{4}'", this.ClubDescription, this.Citta, this.IdRegione.ToString(), this.Telefono, this.EMail);

            DB.DB db = new DB.DB();
            return db.ExecuteNonQuery(strSQL);
        }
    }
}